package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    //todo 1.处理超时支付订单的方法 --- 每隔一分钟触发一次该方法
    //@Scheduled(cron = "0 * * * * ? ")
    public void processTimeOutOrder(){
        //todo 1.1 查询超时的订单 <--> status为1,且时间为<当前时间-15 --> 为超时订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.selectByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);
        if (!CollectionUtils.isEmpty(ordersList)){
            //集合不为空,即集合里都是超时订单,更改其订单状态,取消原因,取消时间
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时,已自动取消订单");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }
    //todo 2.处理一直处于派送中(4)的订单 --- 每天凌晨一点触发一次,让其自动为已完成
    //@Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrder(){
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);//此处为正好12点整,上一天的最后时间
        List<Orders> ordersList = orderMapper.selectByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,time);
        if (!CollectionUtils.isEmpty(ordersList)){
            //集合不为空,即集合里都是处于派送中(4)的订单,更改其订单状态为已完成
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }
    }

}
